local class = require 'hump.class'

Menu = class{
  function(self, background, title, ...)
    self.background = love.graphics.newImage(background)
    self.w = love.graphics.getWidth()
    self.h = love.graphics.getHeight()
    self.title = title
    self.choices = {}
    self:addChoices(unpack({...}))
    self.highlight = 1
    self.choicefont = love.graphics.newFont(12)
    self.titlefont = love.graphics.newFont(20)
    self.fh = self.choicefont:getHeight()
  end
}

function Menu:addChoices(...)
  for k,v in pairs(({...})) do 
    self.choices[k] = v
  end
end

function Menu:highlighted()
  return self.choices[self.highlight]
end

function Menu:setHighlighted(choice)
  if choice <= #self.choices and choice > 0 then
    self.highlight = choice
  end
end

function Menu:highlightPrev()
  self:setHighlighted(self.highlight-1)
end

function Menu:highlightNext()
  self:setHighlighted(self.highlight+1)
end

function Menu:draw()
  love.graphics.draw(self.background)
  local choiceboxh = self.fh*2*#self.choices
  local y = (self.h-choiceboxh)/2
  love.graphics.setFont(self.titlefont)
  love.graphics.printf(self.title, 0, y-self.titlefont:getHeight()*2, self.w, 'center')
  
  love.graphics.setFont(self.choicefont)
  local hwmax = 1
  for k,v in pairs(self.choices) do
    if self.highlight == k then
      love.graphics.setColor(255, 0, 0)
    end
    local hw = self.choicefont:getWidth(v .. '   ')
    if hw > hwmax then
      hwmax = hw
    end
    love.graphics.printf(v, 0, y, self.w, 'center')
    love.graphics.setColor(255, 255, 255)
    y = y + self.fh*2
  end
  love.graphics.rectangle('line', (self.w-hwmax)/2, y-choiceboxh-self.fh, hwmax, choiceboxh+self.fh)
end
